package practice.tmp;

import java.util.ArrayList;
import java.util.List;

public class Solution93 {
    List<String> res = new ArrayList<>();
    List<String> tmp = new ArrayList<>();

    public List<String> restoreIpAddresses(String s) {
        back(s, 0);
        return res;
    }

    public void back(String s, int index) {
        if (tmp.size() == 4) {
            if (index == s.length()) {
                StringBuffer sb = new StringBuffer();
                for (String str : tmp) {
                    sb.append(str).append('.');
                }
                sb.deleteCharAt(sb.length() - 1);
                res.add(sb.toString());
            }
            return;
        }
        for (int i = index; i < s.length(); i++) {
            if (isIP(s.substring(index, i + 1))) {
                tmp.add(s.substring(index, i + 1));
                back(s, i + 1);
                tmp.remove(tmp.size() - 1);
            }
        }
    }

    public boolean isIP(String s) {
        if (s.length() > 1 && s.charAt(0) == '0') return false;
        if (s.length() > 3) return false;
        int i = Integer.parseInt(s);
        return i <= 255;
    }

}
